package com.hao.vertx.web.service.impl;

import com.hao.vertx.core.base.BaseAsyncService;
import com.hao.vertx.web.datasource.JDBCPoolHolder;
import com.hao.vertx.web.entity.Order;
import com.hao.vertx.web.service.OrderService;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonObject;
import io.vertx.jdbcclient.JDBCPool;
import io.vertx.sqlclient.Tuple;
import io.vertx.sqlclient.templates.RowMapper;
import io.vertx.sqlclient.templates.SqlTemplate;

import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class OrderServiceImpl extends BaseAsyncService implements OrderService {

    @Override
    public void findOrderAndItemById(Long orderId, Handler<AsyncResult<JsonObject>> resultHandler) {

        JDBCPool pool = JDBCPoolHolder.getJdbcPool();
        final JsonObject[] jsonObject = {new JsonObject()};
        String sql = "select * from t_order where id=?";
        pool.preparedQuery(sql)
                .execute(Tuple.of(orderId))
                .onFailure(e -> {
                    handleException(e, resultHandler);
                })
                .onSuccess(rows -> {
                    if(rows.iterator().hasNext()){
                        jsonObject[0] = rows.iterator().next().toJson();
                    }

                    String sql2 = "select * from t_order_item where order_id=?";
                    pool.preparedQuery(sql2)
                            .execute(Tuple.of(orderId))
                            .onSuccess(res -> {
                                List<JsonObject> list = new ArrayList<>();
                                res.forEach(r ->  list.add(r.toJson()) );
                                if(!list.isEmpty()) jsonObject[0].put("children", list);

                                resultHandler.handle(Future.succeededFuture(jsonObject[0]));
                            })
                            .onFailure(res -> {
                                resultHandler.handle(Future.succeededFuture(jsonObject[0]));
                            });
                });

        /*JDBCClient client = JDBCClientHolder.getJdbcClient();
        String sql = "select * from t_order where id=?";
        JsonArray params = new JsonArray().add(orderId);
        client.queryWithParams(sql, params, res -> {
            if(res.succeeded()){
                List<JsonObject> lists = res.result().getRows();
                JsonObject jsonObject = lists.isEmpty() ? new JsonObject() : lists.get(0);

                String sql2 = "select * from t_order_item where order_id=?";
                JsonArray params2 = new JsonArray().add(orderId);
                client.queryWithParams(sql2, params2, res2 -> {
                    if(res2.succeeded()){
                        List<JsonObject> lists2 = res2.result().getRows();
                        if(!lists2.isEmpty()) jsonObject.put("children", lists2);
                    }

                    resultHandler.handle(Future.succeededFuture(jsonObject));
                });
            }else{
                handleException(res.cause(), resultHandler);
            }
        });*/
    }


    @Override
    public void listOrderPage(Integer current, Handler<AsyncResult<JsonObject>> resultHandler) {
        JDBCPool pool = JDBCPoolHolder.getJdbcPool();


        JsonObject page = new JsonObject();
        int size = 10;
        int offset = (current - 1) * size;
        page.put("size", size);
        page.put("offset", offset);

        String sql = "select * from t_order order by create_time desc limit #{offset}, #{size}";

        Order.OrderRowMapper orderRowMapper = new Order.OrderRowMapper();
        SqlTemplate.forQuery(pool, sql)
                .mapTo(orderRowMapper.getRowMapper())
                .execute(page.getMap())
                .onFailure(e -> {
                    handleException(e, resultHandler);
                })
                .onSuccess(res -> {
                    List<JsonObject> lists = new ArrayList<>();
                    res.forEach(item -> lists.add(JsonObject.mapFrom(item)) );
                    page.put("rows", lists);

                    resultHandler.handle(Future.succeededFuture(page));
                })
        ;


        /*JsonObject page = new JsonObject();
        page.put("current", current);
        page.put("size", 10);
        int offset = (current - 1) * page.getInteger("size");

        JDBCClient client = JDBCClientHolder.getJdbcClient();

        String sql = "select * from t_order order by create_time desc limit ?, ?";
        JsonArray params = new JsonArray().add(offset).add(page.getInteger("size"));
        client.queryWithParams(sql, params, res -> {
            if(res.succeeded()){
                List<JsonObject> lists = res.result().getRows();
                page.put("rows", lists);

                resultHandler.handle(Future.succeededFuture(page));
            }else{
                handleException(res.cause(), resultHandler);
            }
        });*/
    }

    @Override
    public void deleteOrder(Long orderId, Handler<AsyncResult<Void>> resultHandler) {
        //无事务
        /*orderDao.deleteById(orderId).compose(integer ->
                orderItemDao.deleteByCondition(com.xxx.web.jooq.tables.TOrderItem.T_ORDER_ITEM.ORDER_ID.eq(orderId))
        ).onComplete(ar -> {
            if (ar.succeeded()) {
                resultHandler.handle(Future.succeededFuture());
            } else {
                handleException(ar.cause(), resultHandler);
            }
        });*/
        //有事务
        /*orderDao.queryExecutor().executeAny(dslContext -> {
                    dslContext.transaction(c -> {
                        c.dsl().deleteFrom(com.xxx.web.jooq.tables.TOrder.T_ORDER)
                                .where(com.xxx.web.jooq.tables.TOrder.T_ORDER.ID.eq(orderId)).execute();
                        c.dsl().deleteFrom(com.xxx.web.jooq.tables.TOrderItem.T_ORDER_ITEM)
                                .where(com.xxx.web.jooq.tables.TOrderItem.T_ORDER_ITEM.ORDER_ID.eq(orderId)).execute();
                    });
                    return 0;
                }
        ).onComplete(ar -> {
            if (ar.succeeded()) {
                resultHandler.handle(Future.succeededFuture());
            } else {
                handleException(ar.cause(), resultHandler);
            }
        });*/
    }

    @Override
    public void saveOrder(JsonObject json, Handler<AsyncResult<JsonObject>> resultHandler) {
        /*TOrder tOrder = new TOrder(json);
        Future<Integer> future;
        if (json.containsKey("id") && null != json.getValue("id")) {
            future = orderDao.queryExecutor().executeAny(dslContext -> {
                        UpdateQuery<TOrderRecord> updateQuery = dslContext.updateQuery(com.xxx.web.jooq.tables.TOrder.T_ORDER);
                        Map<String, Object> map = new HashMap<>();
                        if (null != tOrder.getName()) {
                            map.put("name", tOrder.getName());
                        }
                        if (null != tOrder.getUserName()) {
                            map.put("user_name", tOrder.getUserName());
                        }
                        updateQuery.addValues(map);
                        updateQuery.addConditions(com.xxx.web.jooq.tables.TOrder.T_ORDER.ID.eq(tOrder.getId()));
                        return updateQuery.execute();
                    }
            );
            //修改所有字段
            //future = orderDao.update(tOrder);
        } else {
            tOrder.setId(IdWorker.getId()).setCreateTime(LocalDateTime.now());
            future = orderDao.insert(tOrder);
        }
        future.onComplete(ar -> {
            if (ar.succeeded()) {
                resultHandler.handle(Future.succeededFuture(tOrder.toJson()));
            } else {
                handleException(ar.cause(), resultHandler);
            }
        });*/
    }
}
